package com.tcxhb.job.agent.processor.impl;

import com.tcxhb.job.agent.constants.AgentErrorCode;
import com.tcxhb.job.agent.processor.JobProcessor;
import com.tcxhb.job.common.model.MiscResult;
import com.tcxhb.job.common.model.job.JobContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Auther: tcxhb
 * @Date: 2023/11/5
 */
@Slf4j
@Component
public class SpringBeanProcessor implements ApplicationContextAware, SmartInitializingSingleton, JobProcessor {
    private ApplicationContext context;

    private Map<String, JobProcessor> beanMaps = new HashMap<>();

    @Override
    public MiscResult process(JobContext context) {
        JobProcessor processor = beanMaps.get(context.getHandler());
        if(processor == null){
            return MiscResult.err(AgentErrorCode.AGENT_BEAN_NOT_Found);
        }
        return processor.process(context);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    @Override
    public void afterSingletonsInstantiated() {
        String[] beanDefinitionNames = this.context.getBeanNamesForType(JobProcessor.class);
        for (String beanDefinitionName : beanDefinitionNames) {
            Object bean = this.context.getBean(beanDefinitionName);
            String str = bean.getClass().getName();
            //注解在class上
            beanMaps.put(str, (JobProcessor) bean);
        }
    }
}
